package database

import (
	toolsConfig "gitee.com/sansaniot/ssiot-core/config"
	"gitee.com/sansaniot/ssiot-core/facade/runtime"
	log "gitee.com/sansaniot/ssiot-core/logger"
	"gitee.com/sansaniot/ssiot-core/storage/database/dbconfig"
	gormLogger "gitee.com/sansaniot/ssiot-core/storage/database/gorm/logger"
	"gitee.com/sansaniot/ssiot-core/utils"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"time"
)

func SetupDatabase(host string, c *toolsConfig.Database) {
	log.Infof("%s => %s", host, utils.Green(c.Source))
	registers := make([]dbconfig.ResolverConfigure, len(c.Registers))
	for i := range c.Registers {
		registers[i] = dbconfig.NewResolverConfigure(
			c.Registers[i].Sources,
			c.Registers[i].Replicas,
			c.Registers[i].Policy,
			c.Registers[i].Tables)
	}
	resolverConfig := dbconfig.NewConfigure(c.Source, c.MaxIdleConns, c.MaxOpenConns, c.ConnMaxIdleTime, c.ConnMaxLifeTime, registers)
	db, err := resolverConfig.Init(&gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: gormLogger.New(
			logger.Config{
				SlowThreshold: time.Second,
				Colorful:      true,
				LogLevel: logger.LogLevel(
					log.DefaultLogger.Options().Level.LevelForGorm()),
			},
		),
	}, opens[c.Driver])

	if err != nil {
		log.Fatal(utils.Red(c.Driver+" connect error :"), err)
	} else {
		log.Info(utils.Green(c.Driver + " connect success !"))
	}

	runtime.Runtime.SetDb(host, db)
}
